package com.xhwl.centiotdata.suppliersystem.keytopLocal;


import cn.hutool.json.JSONObject;
import com.xhwl.centiotdata.pojo.constant.KeyTopLocalConstant;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.common.pojo.cent.iot.OrgInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author msy
 */
@Slf4j
@Service
public class OrgKeyTopLocalHandler {

    @Autowired
    private GeneralKeyTopLocalHandler generalKeyTopLocalHandler;


    public List<OrgInfo> createOrg(PedestrianIntegrationConfigDTO config, List<OrgInfo> infoList) {
        try {
            infoList.forEach(info -> {
                Map<String,Object> params = new HashMap<>();
                params.put("orgName",info.getOrgName());
                params.put("pid",info.getParentIndexCode());
                log.info("params:{}",params);

                JSONObject jsonData = generalKeyTopLocalHandler.post(KeyTopLocalConstant.SAVE_ORG, params,
                        config.getProjectId(), config.getProductId(),
                        config.getIpAndPort(), config.getLoginName(), config.getPassword());

                JSONObject successes = jsonData.getJSONObject("data");
                info.setOrgIndexCode(successes.getStr("id"));

            });
        } catch (Exception e) {
            log.error("新增组织异常", e);
        }
        return infoList;
    }


    public boolean updateOrg(PedestrianIntegrationConfigDTO config, OrgInfo info) {
        try {
            Map<String,Object>  params = new HashMap<>();
            params.put("id",info.getOrgIndexCode());
            params.put("orgName",info.getOrgName());
            params.put("pid",info.getParentIndexCode());
            log.info("params:{}",params);

            generalKeyTopLocalHandler.post(KeyTopLocalConstant.SAVE_ORG, params,
                    config.getProjectId(), config.getProductId(),
                    config.getIpAndPort(), config.getLoginName(), config.getPassword());
        } catch (Exception e) {
            log.error("修改组织异常", e);
            return false;
        }
        return true;
    }


    public void deleteOrg(PedestrianIntegrationConfigDTO config, OrgInfo info) {
        try {
            JSONObject param = new JSONObject();
            param.put("id", info.getOrgIndexCode());
            JSONObject jsonData = generalKeyTopLocalHandler.post(KeyTopLocalConstant.DELETE_ORG, param,
                    config.getProjectId(), config.getProductId(),
                    config.getIpAndPort(), config.getLoginName(), config.getPassword());
            log.info("组织删除结果:{}", jsonData);
        } catch (Exception e) {
            log.error("删除组织异常", e);
        }
    }

}
